<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2018/3/13
 * Time: 下午3:17
 */
class Upload_model extends CI_Model
{

    public $type = "all";

    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }

    public function do_upload($file, $path = '', $overwrite = true, $encrypt_name = true, $max_size = 2048, $max_width = '', $max_height = '')
    {
        $config['upload_path'] = empty($path) ? $this->config->item("upload_path") : $path;
        if ($this->type == 'all') {
            $config['allowed_types'] = 'gif|jpg|png|jpeg|doc|docx|xls|xlsx|csv|txt';
        } elseif ($this->type == 'pic') {
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
        } elseif ($this->type == 'compress') {
            $config['allowed_types'] = 'tar|rar|zip|7z';
        } elseif ($this->type == 'office') {
            $config['allowed_types'] = 'doc|docx|xls|xlsx|csv|txt';
        }
        $config['max_size']     = $max_size;
        $config['max_width']    = $max_width;
        $config['max_height']   = $max_height;
        $config['overwrite']    = $overwrite;
        $config['encrypt_name'] = $encrypt_name;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($file)) {
            $error = array('error' => $this->upload->display_errors());
            return ['status' => 4004, 'data' => $error];
        } else {
            $data = array('upload_data' => $this->upload->data());
            return ['status' => 0, 'data' => $data];
        }
    }    
}
